/**
 * Licensed under the Apache License Version 2.0.
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package net.interknit.knitter.fw;

import javax.servlet.ServletConfig;

import net.interknit.knitter.fw.hook.AuthenticationHook;
import net.interknit.knitter.fw.init.DefaultInitializer;
import net.interknit.knitter.fw.init.ServerInitializer;

import org.apache.cxf.Bus;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.transport.servlet.CXFServlet;

public class KnitterServlet extends CXFServlet
{
	private final boolean useInInterceptor = true;
	private final boolean useOutInterceptor = true;
	private final boolean useInFaultInterceptor = true;
	private final boolean useOutFaultInterceptor = true;

    @Override
	protected void loadBus(ServletConfig sc)
    {
    	super.loadBus(sc);

    	System.out.println("Interknit: Initializing server...");

    	Bus bus = getBus();

    	bus.getInInterceptors().add(new AuthenticationHook());

		if(useInInterceptor)
			bus.getInInterceptors().add(new LoggingInInterceptor());
		if(useOutInterceptor)
			bus.getOutInterceptors().add(new LoggingOutInterceptor());
		if(useInFaultInterceptor)
			bus.getInFaultInterceptors().add(new LoggingInInterceptor());
		if(useOutFaultInterceptor)
			bus.getOutFaultInterceptors().add(new LoggingOutInterceptor());

    	String customInitalizer = CustomProperties.getCustomProperty(
    			CustomProperties.SERVER_INITIALIZER_NAME);

    	ServerInitializer initializer = null;

    	try
    	{
    		initializer = (ServerInitializer)
    				(Class.forName(customInitalizer).newInstance());
    	}
    	catch(Exception e)
    	{
    		initializer = new DefaultInitializer();
    	}

    	initializer.initialize(bus, sc, null);

    	System.out.println("Interknit: server initialized.");
    }
}
